<template>
  <div class="approve-team-container">
    <el-card
      v-loading="loading"
      class="approve-card"
      :body-style="{ padding: '0' }"
    >
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Lock /></el-icon>
            <span>申请加入公共账号</span>
          </div>
          <div v-if="accountNumber" class="account-info">
            <div class="info-row">
              <el-icon><User /></el-icon>
              <span>团队：{{ teamName }}</span>
            </div>
            <div class="info-row">
              <el-icon><User /></el-icon>
              <span>团队ID：{{ teamUuid }}</span>
            </div>
            <div class="info-row">
              <el-icon><Key /></el-icon>
              <span>账号名称：{{ accountName }}</span>
            </div>
            <div class="info-row">
              <el-icon><Key /></el-icon>
              <span>账号：{{ accountNumber }}</span>
            </div>
          </div>
        </div>
      </template>
      <div class="card-content">
        <template v-if="loading">
          <div class="loading-container">
            <el-icon class="loading-icon">
              <Loading />
            </el-icon>
            <span class="loading-text"
              >正在处理您的账号认证请求，请稍候...</span
            >
          </div>
        </template>
        <template v-else-if="!hasSubmitted">
          <div class="confirm-content">
            <div class="confirm-header">
              <el-icon class="confirm-icon"><InfoFilled /></el-icon>
              <h3>确认加入账号</h3>
            </div>
            <p class="confirm-text">您正在申请加入以下账号：</p>
            <div class="info-container">
              <div class="info-item">
                <el-icon><User /></el-icon>
                <span class="label">团队：</span>
                <span class="value">{{ teamName }}</span>
              </div>
              <div class="info-item">
                <el-icon><User /></el-icon>
                <span class="label">团队ID：</span>
                <span class="value">{{ teamUuid }}</span>
              </div>
              <div class="info-item">
                <el-icon><Key /></el-icon>
                <span class="label">账号名称：</span>
                <span class="value">{{ accountName }}</span>
              </div>
              <div class="info-item">
                <el-icon><Key /></el-icon>
                <span class="label">账号：</span>
                <span class="value">{{ accountNumber }}</span>
              </div>
            </div>
            <div class="confirm-buttons">
              <el-button class="cancel-button" @click="handleCancel">
                <el-icon><Close /></el-icon>
                取消申请
              </el-button>
              <el-button
                type="primary"
                class="confirm-button"
                @click="handleConfirm"
              >
                <el-icon><Check /></el-icon>
                申请加入
              </el-button>
            </div>
          </div>
        </template>
        <template v-else>
          <el-result
            :icon="resultIcon"
            :status="resultStatus"
            :title="resultTitle"
            :sub-title="resultSubTitle"
          />
        </template>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  Loading,
  Lock,
  User,
  Key,
  InfoFilled,
  Close,
  Check
} from "@element-plus/icons-vue";
//import { joinAccount } from "@/api";
import { applyJoinTeamAccount } from "@/api";
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const resultStatus = ref<"success" | "error" | "info">("info");
const resultTitle = ref("处理中");
const resultSubTitle = ref("");
const teamUuid = ref("");
const accountNumber = ref("");
const accountId = ref<number>(0);
const hasSubmitted = ref(false);
const code = ref("");
const teamName = ref("");
const accountName = ref("");

const resultIcon = computed(() => {
  return resultStatus.value;
});

const handleConfirm = async () => {
  try {
    loading.value = true;
    const res = await applyJoinTeamAccount({
      account_id: accountId.value,
      code: code.value
    });

    hasSubmitted.value = true;

    if (res.status === "success") {
      resultStatus.value = "success";
      resultTitle.value = "申请成功";
      resultSubTitle.value = "您的账号使用申请已提交，请等待管理员审批";
    } else {
      resultStatus.value = "error";
      resultTitle.value = "申请失败";
      resultSubTitle.value = res.msg || "申请失败，请稍后重试";
    }
  } catch (error: any) {
    hasSubmitted.value = true;
    resultStatus.value = "error";
    resultTitle.value = "操作失败";
    resultSubTitle.value = error.message || "发生未知错误，请稍后重试";
  } finally {
    loading.value = false;
  }
};

const handleCancel = () => {
  hasSubmitted.value = true;
  resultStatus.value = "info";
  resultTitle.value = "已取消加入";
  resultSubTitle.value = "您已取消加入此账号";
};

onMounted(async () => {
  // 获取完整的URL
  const fullUrl = window.location.href;
  console.log("完整URL:", fullUrl);

  try {
    // 解码URL，处理HTML实体编码
    const decodedUrl = decodeURIComponent(fullUrl.replace(/&amp;/g, "&"));
    console.log("解码后的URL:", decodedUrl);

    // 提取所有查询参数部分
    const hashParts = decodedUrl.split("#/");
    if (hashParts.length < 2) {
      throw new Error("URL格式错误：缺少路由部分");
    }

    const routeParts = hashParts[1].split("?");
    if (routeParts.length < 2) {
      throw new Error("URL格式错误：缺少参数部分");
    }

    // 获取所有参数字符串
    const allParams = routeParts.slice(1).join("?");
    console.log("所有参数:", allParams);

    // 先处理主要参数
    const mainParamsMatch = allParams.match(/^([^?]+)/);
    const mainParams = mainParamsMatch ? mainParamsMatch[1] : "";
    console.log("主要参数:", mainParams);

    // 获取最后的OAuth code
    const oauthCodeMatch = allParams.match(/[?]code=([^&]+)$/);
    const oauthCode = oauthCodeMatch ? oauthCodeMatch[1] : null;
    console.log("OAuth Code:", oauthCode);

    const searchParams = new URLSearchParams(mainParams);
    const uuid = searchParams.get("uuid");
    const account = searchParams.get("account_number");
    const parsedAccountId = searchParams.get("account_id");
    const parsedTeamName = searchParams.get("team_name");
    const parsedAccountName = searchParams.get("account_name");

    console.log("解析结果:", {
      uuid,
      account,
      accountId: parsedAccountId,
      teamName: parsedTeamName,
      accountName: parsedAccountName,
      oauthCode
    });

    // 验证所有必需参数
    if (!uuid || !account || !parsedAccountId || !oauthCode) {
      throw new Error(
        `缺少必需参数: ${[
          !uuid && "uuid",
          !account && "account_number",
          !parsedAccountId && "account_id",
          !oauthCode && "code"
        ]
          .filter(Boolean)
          .join(", ")}`
      );
    }

    // 设置值
    teamUuid.value = uuid;
    accountNumber.value = account;
    accountId.value = parseInt(parsedAccountId, 10);
    code.value = oauthCode;
    teamName.value = parsedTeamName || "";
    accountName.value = parsedAccountName || "";
  } catch (error: any) {
    console.error("参数解析错误:", error);
    hasSubmitted.value = true;
    resultStatus.value = "error";
    resultTitle.value = "参数错误";
    resultSubTitle.value = error.message || "参数解析失败";
  }
});
</script>

<style lang="scss" scoped>
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.approve-team-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);

  .approve-card {
    width: 100%;
    max-width: 500px;
    border-radius: 8px;
    box-shadow: 0 4px 24px rgb(0 0 0 / 10%);
    transition: all 0.3s ease;

    @media screen and (width <= 768px) {
      margin: 0 8px;
    }

    .card-header {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      align-items: center;
      justify-content: space-between;
      padding: 16px;
      background: linear-gradient(to right, #fff, #f8f9fa);
      border-bottom: 1px solid #ebeef5;

      @media screen and (width <= 480px) {
        flex-direction: column;
        align-items: flex-start;
      }

      .header-left {
        display: flex;
        gap: 8px;
        align-items: center;
        min-width: 120px;

        .header-icon {
          font-size: 20px;
          color: #409eff;
        }

        span {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }

      .account-info {
        .info-row {
          display: flex;
          gap: -1px;
          align-items: center;
          max-width: 100%;
          margin-bottom: 4px;
          overflow: hidden;
          font-size: 13px;
          color: #606266;
          text-overflow: ellipsis;
          white-space: nowrap;

          .el-icon {
            flex-shrink: 0;
            font-size: 14px;
            color: #909399;
          }

          span {
            overflow: hidden;
            text-overflow: ellipsis;
          }

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }

    .card-content {
      padding: 20px 16px;

      .loading-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 40px 0;

        .loading-icon {
          margin-bottom: 16px;
          font-size: 32px;
          color: #409eff;
          animation: rotate 1s linear infinite;
        }

        .loading-text {
          font-size: 14px;
          color: #606266;
        }
      }

      .confirm-content {
        .confirm-header {
          display: flex;
          gap: 8px;
          align-items: center;
          justify-content: center;
          margin-bottom: 20px;

          .confirm-icon {
            flex-shrink: 0;
            font-size: 24px;
            color: #409eff;
          }

          h3 {
            margin: 0;
            font-size: 18px;
            color: #303133;
          }
        }

        .confirm-text {
          margin-bottom: 20px;
          font-size: 14px;
          color: #606266;
          text-align: center;
        }

        .info-container {
          padding: 16px;
          margin-bottom: 20px;
          background: #f8f9fa;
          border-radius: 8px;

          .info-item {
            display: flex;
            gap: 8px;
            align-items: center;
            padding: 8px 0;
            overflow: hidden;

            .el-icon {
              flex-shrink: 0;
              font-size: 16px;
              color: #909399;
            }

            .label {
              flex-shrink: 0;
              font-size: 14px;
              color: #909399;
            }

            .value {
              overflow: hidden;
              font-size: 14px;
              font-weight: 500;
              color: #303133;
              text-overflow: ellipsis;
            }
          }
        }

        .confirm-buttons {
          display: flex;
          flex-wrap: wrap;
          gap: 12px;
          justify-content: center;
          margin-top: 24px;

          .el-button {
            display: flex;
            flex: 1;
            gap: 6px;
            align-items: center;
            justify-content: center;
            min-width: 120px;
            max-width: 200px;
            padding: 10px 20px;

            @media screen and (width <= 480px) {
              width: 100%;
              max-width: none;
            }

            .el-icon {
              flex-shrink: 0;
              font-size: 16px;
            }
          }
        }
      }
    }
  }
}

// 添加过渡动画
.el-card {
  animation: fade-in 0.3s ease-out;
}
</style>
